package controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.DBHelper;
import model.User;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import form.RegistrationForm;

public class RegisterAction2 extends Action {

	private Logger logger = Logger.getLogger(RegisterAction2.class);

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String inputEmail = request.getParameter("email");
		String inputPwd = request.getParameter("password");
		if ( ! DBHelper.areCredentialsCorrect(inputEmail, inputPwd ) ) {
			ActionMessages errors = new ActionMessages();
			
			errors.add( "credentials", new ActionMessage("error.bad-credentials")) ;
			
			saveErrors(request, errors);
			
			return mapping.findForward("bad-credentials");
		} else {
			
			// The user credentials are correct, let's store the User in the HttpSession so that
			// we prevent from logging the same user twice.

			int userId = DBHelper.getId(inputEmail, inputPwd);

			User user = DBHelper.getUserList().get(userId);
			
			logger.info(String.format("Login success. Setting the user(%d,%s) to the session=%s", user.getId(), user.getEmail(), request.getSession()));
			
			request.getSession().setAttribute("user", user);
			
			return mapping.findForward("success");
		}
	}
}
